#!/usr/bin/env python3

import argparse
import os

from utils import *


def main():
    args = argparse.ArgumentParser()
    args.add_argument('bin_path')
    args.add_argument('-o', '--output', required=True)
    args.add_argument('-p', '--prefix')
    args.add_argument('-v', '--verbose', action='store_true')
    args = args.parse_args()

    bin_path = args.bin_path
    out_path = args.output
    out_prefix = args.prefix
    verbose = args.verbose
    if verbose:
        info(f'Binary to C with args {args}')
    if not os.path.isfile(bin_path):
        raise FileNotFoundError(bin_path)
    with open(bin_path, 'rb') as bin_file:
        bin_content = bin_file.read()
    out_array = tuple(map(lambda b: f'0x{b:02x}', bin_content))
    out_array_name = f'{os.path.basename(bin_path)}'.split(r'.')[0]
    if out_prefix:
        out_array_name = f'{out_prefix}_{out_array_name}'
    if verbose:
        info(f'Converting binary file {bin_path} to bytes array')
    out_content = f'''// Generated by {os.path.basename(__file__)}
#include <elf.h>
#include <kern/multitask/partition.h>

static const uint8_t {out_array_name}_bin[]
__aligned(sizeof(Elf64_Ehdr)) = {{{','.join(out_array)}}};

static struct prog_def_t {out_array_name} = {{
    .pg_name = "{out_array_name}",
    .pg_elf_bin = {out_array_name}_bin,
    .pg_elf_size = {len(out_array)},
}};

link_prog({out_array_name});
'''
    if verbose:
        info(f'Writing result to file {out_path}')
    with open(out_path, 'w', encoding='utf-8') as out_file:
        out_file.write(out_content)


if __name__ == '__main__':
    main()
